<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      <div>
        <h2 class="text-2xl font-bold">模板库</h2>
        <p class="text-gray-500 mt-1">选择合适的模板快速创建页面，支持按类型筛选</p>
      </div>
      
      <div class="flex flex-wrap gap-3">
        <div class="relative">
          <input 
            type="text" 
            placeholder="搜索模板..." 
            class="form-input pl-10 w-full sm:w-auto"
            v-model="searchKeyword"
          >
          <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        </div>
        
        <button class="btn btn-secondary" @click="resetFilters">
          <i class="fa fa-refresh"></i>
          <span>重置筛选</span>
        </button>
      </div>
    </div>
    
    <!-- 模板分类筛选 -->
    <div class="card p-4">
      <div class="flex flex-wrap items-center gap-2">
        <span class="text-sm font-medium text-gray-700 whitespace-nowrap">模板分类：</span>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'all' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'all'"
        >
          全部模板
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'home' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'home'"
        >
          首页模板
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'about' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'about'"
        >
          关于我们
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'products' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'products'"
        >
          产品展示
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'news' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'news'"
        >
          新闻资讯
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'contact' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'contact'"
        >
          联系我们
        </button>
        <button 
          class="px-3 py-1 rounded-full text-sm"
          :class="activeCategory === 'landing' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          @click="activeCategory = 'landing'"
        >
          活动专题
        </button>
      </div>
    </div>
    
    <!-- 模板展示 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        class="card overflow-hidden group hover:shadow-md transition-shadow duration-300"
        v-for="template in paginatedTemplates" 
        :key="template.id"
      >
        <!-- 模板预览图 -->
        <div class="relative overflow-hidden aspect-[4/3] bg-gray-100">
          <img 
            :src="template.previewUrl" 
            :alt="template.name" 
            class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
          >
          <div class="absolute top-3 right-3">
            <span 
              class="badge"
              :class="getCategoryBadgeClass(template.category)"
            >
              {{ getCategoryName(template.category) }}
            </span>
          </div>
          <div class="absolute inset-0 bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center gap-3">
            <button 
              class="btn btn-secondary"
              @click.stop="previewTemplate(template.id)"
            >
              <i class="fa fa-eye"></i>
              <span>预览</span>
            </button>
            <button 
              class="btn btn-primary"
              @click.stop="useTemplate(template.id)"
            >
              <i class="fa fa-check"></i>
              <span>使用</span>
            </button>
          </div>
        </div>
        
        <!-- 模板信息 -->
        <div class="p-4">
          <div class="flex justify-between items-start">
            <div>
              <h3 class="font-medium">{{ template.name }}</h3>
              <p class="text-sm text-gray-500 mt-1">{{ template.description }}</p>
            </div>
            <div class="flex items-center gap-1 text-warning text-sm">
              <i class="fa fa-star"></i>
              <span>{{ template.rating }}</span>
            </div>
          </div>
          
          <div class="mt-3 flex justify-between items-center">
            <div class="flex items-center gap-2 text-sm text-gray-500">
              <span><i class="fa fa-download mr-1"></i> {{ template.downloads }}次使用</span>
              <span><i class="fa fa-clock-o mr-1"></i> {{ template.updateTime }}</span>
            </div>
            <button 
              class="text-primary text-sm hover:underline"
              @click="showDetails(template.id)"
            >
              查看详情
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 无结果提示 -->
    <div v-if="filteredTemplates.length === 0" class="text-center py-16">
      <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
        <i class="fa fa-folder-open-o text-2xl text-gray-400"></i>
      </div>
      <h3 class="text-lg font-medium mb-2">未找到匹配的模板</h3>
      <p class="text-gray-500 max-w-md mx-auto">
        没有找到符合当前筛选条件的模板，请尝试调整搜索关键词或分类筛选条件
      </p>
      <button 
        class="mt-4 btn btn-secondary"
        @click="resetAllFilters"
      >
        <i class="fa fa-refresh mr-1"></i> 查看全部模板
      </button>
    </div>
    
    <!-- 分页 -->
    <div v-if="filteredTemplates.length > 0" class="flex items-center justify-between py-4">
      <div class="text-sm text-gray-500">
        显示 {{ Math.min((currentPage-1)*pageSize + 1, filteredTemplates.length) }} - {{ Math.min(currentPage*pageSize, filteredTemplates.length) }} 条，共 {{ filteredTemplates.length }} 条模板
      </div>
      <div class="flex items-center gap-2">
        <button 
          class="w-9 h-9 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
          :disabled="currentPage === 1"
          @click="currentPage = currentPage - 1"
        >
          <i class="fa fa-chevron-left text-xs"></i>
        </button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          class="w-9 h-9 flex items-center justify-center rounded"
          :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
        
        <button 
          class="w-9 h-9 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
          :disabled="currentPage === totalPages"
          @click="currentPage = currentPage + 1"
        >
          <i class="fa fa-chevron-right text-xs"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 模板数据
const templates = ref([
  {
    id: 1,
    name: "现代企业首页",
    description: "简洁大气的企业官网首页模板，适合各类企业使用",
    previewUrl: "https://picsum.photos/id/1048/800/600",
    category: "home",
    rating: 4.8,
    downloads: 1254,
    updateTime: "2023-06-15",
    components: [
      { type: "slider", name: "首页轮播图", images: ["https://picsum.photos/id/1048/1200/400", "https://picsum.photos/id/1059/1200/400"] },
      { type: "text", name: "企业标语", content: "创新科技，引领未来", style: { fontSize: "28px", textAlign: "center" } },
      { type: "row", name: "服务展示行", children: [
        { type: "column", name: "服务列1", children: [{ type: "text", name: "服务1", content: "专业咨询" }] },
        { type: "column", name: "服务列2", children: [{ type: "text", name: "服务2", content: "技术支持" }] },
        { type: "column", name: "服务列3", children: [{ type: "text", name: "服务3", content: "售后服务" }] }
      ]}
    ]
  },
  {
    id: 2,
    name: "产品展示详情页",
    description: "精美的产品展示模板，支持多图展示和详细参数",
    previewUrl: "https://picsum.photos/id/26/800/600",
    category: "products",
    rating: 4.7,
    downloads: 987,
    updateTime: "2023-05-28",
    components: [
      { type: "row", name: "产品标题行", children: [
        { type: "text", name: "产品名称", content: "智能手环 Pro", style: { fontSize: "24px", fontWeight: "bold" } }
      ]},
      { type: "row", name: "产品展示行", children: [
        { type: "slider", name: "产品图片", images: ["https://picsum.photos/id/26/600/600", "https://picsum.photos/id/96/600/600"] },
        { type: "column", name: "产品信息列", children: [
          { type: "text", name: "产品价格", content: "¥199.00", style: { fontSize: "28px", color: "#F53F3F" } },
          { type: "form", name: "规格选择", fields: [
            { type: "radio", name: "color", label: "颜色", options: ["黑色", "白色", "蓝色"] }
          ]},
          { type: "button", name: "购买按钮", text: "立即购买", style: { backgroundColor: "#F53F3F", color: "white" } }
        ]}
      ]}
    ]
  },
  {
    id: 3,
    name: "公司简介页面",
    description: "展示公司历史、文化和团队的专业模板",
    previewUrl: "https://picsum.photos/id/42/800/600",
    category: "about",
    rating: 4.5,
    downloads: 753,
    updateTime: "2023-06-02",
    components: [
      { type: "text", name: "页面标题", content: "关于我们", style: { fontSize: "32px", textAlign: "center" } },
      { type: "text", name: "公司简介", content: "我们成立于2010年，专注于提供高品质的产品和服务...", style: { lineHeight: "1.8" } },
      { type: "row", name: "团队展示", children: [
        { type: "column", name: "团队成员1", children: [
          { type: "image", name: "成员照片", url: "https://picsum.photos/id/1005/300/300" },
          { type: "text", name: "成员姓名", content: "张明 - CEO" }
        ]},
        { type: "column", name: "团队成员2", children: [
          { type: "image", name: "成员照片", url: "https://picsum.photos/id/1006/300/300" },
          { type: "text", name: "成员姓名", content: "李华 - 技术总监" }
        ]}
      ]}
    ]
  },
  {
    id: 4,
    name: "新闻资讯列表",
    description: "简洁的新闻资讯展示模板，支持分类和搜索",
    previewUrl: "https://picsum.photos/id/24/800/600",
    category: "news",
    rating: 4.6,
    downloads: 621,
    updateTime: "2023-05-19",
    components: [
      { type: "text", name: "页面标题", content: "最新资讯", style: { fontSize: "28px" } },
      { type: "list", name: "新闻列表", items: [
        { title: "公司新产品发布", date: "2023-06-10", content: "我们很高兴地宣布，新一代产品将于下月正式上市..." },
        { title: "年度总结大会顺利召开", date: "2023-05-28", content: "公司年度总结大会在总部顺利召开，回顾过去一年的成就..." },
        { title: "加入我们的团队", date: "2023-05-15", content: "我们正在寻找有才华的专业人士加入我们的团队..." }
      ]}
    ]
  },
  {
    id: 5,
    name: "联系我们页面",
    description: "包含表单和地图的联系页面模板",
    previewUrl: "https://picsum.photos/id/48/800/600",
    category: "contact",
    rating: 4.4,
    downloads: 589,
    updateTime: "2023-06-10",
    components: [
      { type: "text", name: "页面标题", content: "联系我们", style: { fontSize: "28px" } },
      { type: "row", name: "联系信息行", children: [
        { type: "column", name: "联系表单列", children: [
          { type: "form", name: "联系表单", fields: [
            { type: "input", name: "name", label: "您的姓名" },
            { type: "input", name: "email", label: "电子邮箱" },
            { type: "textarea", name: "message", label: "留言内容" },
            { type: "button", name: "提交按钮", text: "发送留言" }
          ]}
        ]},
        { type: "column", name: "联系信息列", children: [
          { type: "text", name: "公司地址", content: "北京市朝阳区XX大厦A座1001室" },
          { type: "text", name: "联系电话", content: "400-123-4567" },
          { type: "text", name: "电子邮箱", content: "contact@example.com" },
          { type: "map", name: "公司位置", address: "北京市朝阳区XX大厦" }
        ]}
      ]}
    ]
  },
  {
    id: 6,
    name: "促销活动专题页",
    description: "吸引眼球的活动专题页面，提高转化率",
    previewUrl: "https://picsum.photos/id/60/800/600",
    category: "landing",
    rating: 4.9,
    downloads: 1452,
    updateTime: "2023-06-20",
    components: [
      { type: "slider", name: "活动轮播", images: ["https://picsum.photos/id/60/1200/500", "https://picsum.photos/id/26/1200/500"] },
      { type: "text", name: "活动标题", content: "618年中大促", style: { fontSize: "36px", textAlign: "center", color: "#F53F3F" } },
      { type: "text", name: "活动时间", content: "活动时间：2023-06-01 至 2023-06-18", style: { textAlign: "center" } },
      { type: "row", name: "活动商品行", children: [
        { type: "column", name: "商品1", children: [
          { type: "image", name: "商品图片", url: "https://picsum.photos/id/96/400/400" },
          { type: "text", name: "商品名称", content: "智能手表" },
          { type: "text", name: "商品价格", content: "¥299 <span style='text-decoration: line-through'>¥399</span>", style: { color: "#F53F3F" } },
          { type: "button", name: "购买按钮", text: "立即抢购" }
        ]},
        { type: "column", name: "商品2", children: [
          { type: "image", name: "商品图片", url: "https://picsum.photos/id/26/400/400" },
          { type: "text", name: "商品名称", content: "无线耳机" },
          { type: "text", name: "商品价格", content: "¥199 <span style='text-decoration: line-through'>¥299</span>", style: { color: "#F53F3F" } },
          { type: "button", name: "购买按钮", text: "立即抢购" }
        ]}
      ]}
    ]
  },
  {
    id: 7,
    name: "科技公司首页",
    description: "充满科技感的企业首页，适合科技类公司",
    previewUrl: "https://picsum.photos/id/180/800/600",
    category: "home",
    rating: 4.7,
    downloads: 856,
    updateTime: "2023-05-25",
    components: [
      { type: "row", name: "导航行", children: [
        { type: "text", name: "公司名称", content: "TechFuture", style: { fontSize: "24px", fontWeight: "bold" } },
        { type: "text", name: "导航菜单", content: "首页 | 产品 | 解决方案 | 关于我们 | 联系" }
      ]},
      { type: "slider", name: "科技轮播", images: ["https://picsum.photos/id/180/1200/500", "https://picsum.photos/id/160/1200/500"] },
      { type: "text", name: "公司口号", content: "引领科技前沿，创造智能未来", style: { fontSize: "28px", textAlign: "center" } },
      { type: "row", name: "产品展示", children: [
        { type: "column", name: "产品1", children: [
          { type: "image", name: "产品图", url: "https://picsum.photos/id/160/400/300" },
          { type: "text", name: "产品名", content: "AI智能系统" }
        ]},
        { type: "column", name: "产品2", children: [
          { type: "image", name: "产品图", url: "https://picsum.photos/id/119/400/300" },
          { type: "text", name: "产品名", content: "物联网平台" }
        ]}
      ]}
    ]
  },
  {
    id: 8,
    name: "电商产品列表",
    description: "适合电商网站的产品列表展示模板",
    previewUrl: "https://picsum.photos/id/21/800/600",
    category: "products",
    rating: 4.6,
    downloads: 1123,
    updateTime: "2023-06-05",
    components: [
      { type: "text", name: "页面标题", content: "全部商品", style: { fontSize: "28px" } },
      { type: "form", name: "筛选表单", fields: [
        { type: "select", name: "category", label: "商品分类", options: ["全部", "电子产品", "服装鞋帽", "家居用品"] },
        { type: "select", name: "sort", label: "排序方式", options: ["默认", "价格从低到高", "价格从高到低", "销量优先"] }
      ]},
      { type: "grid", name: "商品网格", columns: 3, children: [
        { type: "column", name: "商品项1", children: [
          { type: "image", name: "商品图", url: "https://picsum.photos/id/21/300/300" },
          { type: "text", name: "商品名", content: "时尚休闲鞋" },
          { type: "text", name: "价格", content: "¥259", style: { color: "#F53F3F" } },
          { type: "button", name: "加入购物车", text: "加入购物车" }
        ]},
        { type: "column", name: "商品项2", children: [
          { type: "image", name: "商品图", url: "https://picsum.photos/id/26/300/300" },
          { type: "text", name: "商品名", content: "智能手环" },
          { type: "text", name: "价格", content: "¥199", style: { color: "#F53F3F" } },
          { type: "button", name: "加入购物车", text: "加入购物车" }
        ]},
        { type: "column", name: "商品项3", children: [
          { type: "image", name: "商品图", url: "https://picsum.photos/id/96/300/300" },
          { type: "text", name: "商品名", content: "无线耳机" },
          { type: "text", name: "价格", content: "¥299", style: { color: "#F53F3F" } },
          { type: "button", name: "加入购物车", text: "加入购物车" }
        ]}
      ]}
    ]
  },
  {
    id: 9,
    name: "教育机构首页",
    description: "适合学校和培训机构的首页模板",
    previewUrl: "https://picsum.photos/id/20/800/600",
    category: "home",
    rating: 4.5,
    downloads: 789,
    updateTime: "2023-06-18",
    components: [
      { type: "slider", name: "Banner轮播", images: ["https://picsum.photos/id/20/1200/400", "https://picsum.photos/id/42/1200/400"] },
      { type: "text", name: "机构名称", content: "未来教育学院", style: { fontSize: "32px", textAlign: "center" } },
      { type: "text", name: "办学理念", content: "培养未来领袖，塑造美好人生", style: { textAlign: "center", fontSize: "18px" } },
      { type: "row", name: "课程展示", children: [
        { type: "column", name: "课程1", children: [
          { type: "image", name: "课程图片", url: "https://picsum.photos/id/42/400/300" },
          { type: "text", name: "课程名称", content: "编程入门班" },
          { type: "text", name: "课程简介", content: "适合零基础学员，掌握编程基础知识" }
        ]},
        { type: "column", name: "课程2", children: [
          { type: "image", name: "课程图片", url: "https://picsum.photos/id/20/400/300" },
          { type: "text", name: "课程名称", content: "英语强化班" },
          { type: "text", name: "课程简介", content: "提升听说读写能力，适合各年龄段" }
        ]}
      ]},
      { type: "button", name: "咨询报名", text: "立即咨询", style: { margin: "0 auto", display: "block" } }
    ]
  }
])

// 筛选条件
const activeCategory = ref('all')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(6)

// 筛选后的模板
const filteredTemplates = computed(() => {
  return templates.value.filter(template => {
    // 分类筛选
    const categoryMatch = activeCategory.value === 'all' || template.category === activeCategory.value
    // 关键词筛选
    const keywordMatch = !searchKeyword.value || 
      template.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      template.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    
    return categoryMatch && keywordMatch
  })
})

// 分页处理
const paginatedTemplates = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredTemplates.value.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredTemplates.value.length / pageSize.value)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxDisplay = 5 // 最多显示5个页码
  let startPage = Math.max(1, currentPage.value - Math.floor(maxDisplay / 2))
  const endPage = Math.min(totalPages.value, startPage + maxDisplay - 1)
  
  // 调整起始页，确保显示足够的页码
  if (endPage - startPage + 1 < maxDisplay) {
    startPage = Math.max(1, endPage - maxDisplay + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 监听筛选条件变化，重置当前页码
watch([activeCategory, searchKeyword], () => {
  currentPage.value = 1
})

// 获取分类名称
const getCategoryName = (category) => {
  const names = {
    'home': '首页',
    'about': '关于我们',
    'products': '产品展示',
    'news': '新闻资讯',
    'contact': '联系我们',
    'landing': '活动专题'
  }
  return names[category] || '其他'
}

// 获取分类标签样式
const getCategoryBadgeClass = (category) => {
  const classes = {
    'home': 'bg-primary/10 text-primary',
    'about': 'bg-secondary/10 text-secondary',
    'products': 'bg-success/10 text-success',
    'news': 'bg-warning/10 text-warning',
    'contact': 'bg-purple-100 text-purple-600',
    'landing': 'bg-danger/10 text-danger'
  }
  return classes[category] || 'bg-gray-100 text-gray-600'
}

// 重置筛选条件（保留分类）
const resetFilters = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

// 重置所有筛选条件
const resetAllFilters = () => {
  activeCategory.value = 'all'
  searchKeyword.value = ''
  currentPage.value = 1
}

// 预览模板
const previewTemplate = (id) => {
  // 在实际应用中，这里应该打开一个预览窗口展示模板效果
  const template = templates.value.find(t => t.id === id)
  if (template) {
    alert(`预览模板: ${template.name}\n\n描述: ${template.description}`)
    // 实际项目中可以使用window.open打开预览页面
    // window.open(`/preview?templateId=${id}`, '_blank')
  }
}

// 使用模板（跳转到编辑器）
const useTemplate = (id) => {
  router.push({
    path: '/visual-editor',
    query: { templateId: id }
  })
}

// 查看模板详情
const showDetails = (id) => {
  const template = templates.value.find(t => t.id === id)
  if (template) {
    alert(`模板详情: ${template.name}\n\n分类: ${getCategoryName(template.category)}\n评分: ${template.rating}\n使用次数: ${template.downloads}次\n最后更新: ${template.updateTime}\n\n${template.description}`)
  }
}
</script>